<script setup lang="ts">
	import { ref, onMounted, toRaw, getCurrentInstance } from "vue";
	import { formRules } from "./utils/rule";
	import { FormProps } from "./utils/types";
	import ReCol from "@/components/ReCol";
  import { baseUrlApi, baseOaApi } from "@/api/utils";
  import type { UploadProps } from "element-plus";
  import { message } from "@/utils/message";
  import { QuillEditor, Quill } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import { uploadFileApi } from "@/api/uploadFile";
  import ImageUploader from "quill-image-uploader";
	const props = withDefaults(defineProps<FormProps>(), {
		formInline: () => ({
			title: "",
			status: 0,
			Id: 0,
		})
	});
	const ruleFormRef = ref();
	const newFormInline = ref(props.formInline);
	function getRef() {
		return ruleFormRef.value;
	}
	defineExpose({ getRef });
  Quill.register("modules/imageUploader", ImageUploader);
  onMounted(()=> {
    if(newFormInline.value.attachment && newFormInline.value.attachment.length > 0) {
      for (let item of newFormInline.value.attachment) {
        fileList.value.push({
          name: item,
          url: item
        })
      }

    }
  })
  const actionUrl = baseUrlApi + "/uploadFile/upload";
  const myQuillEditor = ref(null);
  const fileList = ref([])
  const handleAttachmentSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
  ) => {
    // imgUrl.value = URL.createObjectURL(uploadFile.raw!);
    newFormInline.value.attachment = []
    for (let item of fileList.value) {
      if(item?.url) {
        newFormInline.value.attachment.push(item?.url)
      } else {
        newFormInline.value.attachment.push(baseOaApi + item?.response?.result?.path)
      }

    }
  };
  const beforeUpload = (file) => {

  }
  const imageHandler = () => {
    // 创建一个文件输入元素
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    // 模拟点击，打开文件选择对话框
    input.click();

    // 当用户选择文件后触发的事件
    input.onchange = async (e) => {
      // 获取用户选择的文件
      // const file = e.target.files[0];
      const file = input.files ? input.files[0] : null;
      if (file) {
        // 创建一个 FormData 对象，用于文件上传
        const formData = new FormData();
        formData.append('file', file);
        try {
          /**
           * @todo 可以选中图片，然后把file文件给后端，后端给存到文件服务器，然后返回一个线上地址
           * 这里的abc替换成你的请求接口方法,也可以使用 axios 发送 POST 请求
           * */
          // todo
          // 使用 axios 发送 POST 请求，将文件上传到服务器,这里的abc替换成你的请求接口方法
          // 可以选中图片，然后把file文件给后端，后端给存到文件服务器，然后返回一个线上地址
          const res = await uploadFileApi(formData);
          // 确保获取到 Quill 编辑器实例
          const quill = toRaw(editorRef.value).getQuill()
          if (quill) {
            // 获取当前光标位置
            const range = quill.getSelection(true);
            // 在当前光标位置插入上传的图片
            quill.insertEmbed(range.index, 'image', baseOaApi + res?.result?.path);
          }
        } catch (error) {
          alert('图片上传失败')
        }
      }
    };
  }
  const editorRef = ref();
  const uploadRef = ref()
  const options = ref({
    theme:"snow",
    modules: {
      // 富文本头部栏的功能配置
      toolbar: {
        container: [
          ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
          [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
          [{ align: [] }], // 对齐方式
          [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
          [{ font: [] }], // 字体种类
          [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
          [{ direction: 'ltl' }], // 文本方向
          [{ direction: 'rtl' }], // 文本方向
          [{ indent: '-1' }, { indent: '+1' }], // 缩进
          [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
          [{ script: 'sub' }, { script: 'super' }], // 上标/下标
          ['blockquote', 'code-block'], // 引用  代码块
          ['clean'], // 清除文本格式
          ['link', 'image'], // 链接、图片、视频
        ],
        handlers: {
          image: imageHandler, // 点击图片触发事件
        },

      },

    }
  })
</script>

<template>
	<el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="auto">
    <el-row :gutter="30">
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="标题" prop="notepadTitle">
          <el-input v-model="newFormInline.notepadTitle" clearable placeholder="请输入标题" />
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24" style="height: 400px;">
      	<el-form-item label="内容" prop="content">
          <!-- <el-input v-model="newFormInline.content" clearable placeholder="请输入内容" /> -->
          <div class="editor w-full">
            <quill-editor v-model:content="newFormInline.content" ref="editorRef"
            contentType="html" style="height: 300px;" :options="options">
            </quill-editor>
          </div>
      	</el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
      	<el-form-item label="附件">
      		<el-upload
            class="sty-upload"
      		  ref="uploadRef"
      		  :action="actionUrl"
      		  :on-success="handleAttachmentSuccess"
      		  v-model:file-list="fileList"
      		  :before-upload="beforeUpload"
            style="width: 100%;"
            drag
      		  multiple>
      		  <el-button style="margin-left: 10px;" link size="small" type="primary">上传附件</el-button>
      		</el-upload>
      	</el-form-item>
      </re-col>

    </el-row>
	</el-form>
</template>
<style scoped>
:deep(.ql-snow .ql-tooltip[data-mode=link]::before) {
  content: "请输入链接地址:";
}
:deep(.ql-snow .ql-tooltip.ql-editing a.ql-action::after) {
  border-right: 0px;
  content: '保存';
  padding-right: 0px;
}

:deep(.ql-snow .ql-tooltip[data-mode=video]::before){
  content: "请输入视频地址:";
}

:deep(.ql-snow .ql-picker.ql-size .ql-picker-label::before),
:deep(.ql-snow .ql-picker.ql-size .ql-picker-item::before) {
  content: '14px';
}
:deep(.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before),
:deep(.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before) {
  content: '10px';
}
:deep(.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before),
:deep(.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before) {
  content: '18px';
}
:deep(.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before),
:deep(.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before ){
  content: '32px';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item::before) {
  content: '文本';
}
:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before) {
  content: '标题1';
}
:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before) {
  content: '标题2';
}
:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before),
:deep( .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before){
  content: '标题3';
}
:deep( .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before)  {
  content: "标题4";
}
:deep( .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before) ,
:deep( .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before)  {
  content: '标题5';
}
:deep( .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before)  {
  content: '标题6';
}

:deep(.ql-snow .ql-picker.ql-font .ql-picker-label::before),
:deep(.ql-snow .ql-picker.ql-font .ql-picker-item::before) {
  content: '标准字体';
}
:deep(.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before),
:deep(.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before) {
  content: '衬线字体';
}
:deep(.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before),
:deep(.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before) {
  content: '等宽字体';
}
:deep(.ql-align-center) {
  text-align: center;
}
:deep(.ql-align-right) {
  text-align: right;
}
:deep(.ql-align-left){
  text-align: left;
}
</style>
